package Demo1;

import java.util.concurrent.Callable;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: homechen
 * Date: 2024-03-10
 * Time: 13:54
 */
public class ThreadDemo {

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            LockSupport.park();
            System.out.println("线程 1 休眠结束！");
        }, "线程 1");
        t1.start();
        Thread t2 = new Thread(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("唤醒线程 1！");
            LockSupport.unpark(t1);
        }, "线程 2");

        t2.start();
    }


//    public static void main(String[] args) {
//        // 创建 condition 对象
//        Lock lock = new ReentrantLock(); // 这个lock是一个接口
//        Condition condition1 = lock.newCondition(); // 条件变量 1
//        Condition condition2 = lock.newCondition(); // 条件变量 2
//        // 先加锁
//        lock.lock();
//        try {
//            // 业务逻辑
//            System.out.println("进入等待！");
//            condition1.await();
//            // 唤醒操作
//            condition1.signal();
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        } finally {
//            lock.unlock(); // 手动释放锁
//        }
//    }


//    public static void main(String[] args) throws InterruptedException {
//        Object lock = new Object();
//        new Thread(() -> {
//            System.out.println("线程开始执行！");
//            synchronized (lock) {
//                try {
//                    System.out.println("线程进入等待！");
//                    lock.wait(); // 线程会释放锁
//                    System.out.println("线程继续执行！");
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
//                System.out.println("线程执行结束！");
//            }
//        }).start();
//
//        Thread.sleep(1000);
//        System.out.println("执行 notify()！");
//        synchronized (lock) {
//            lock.notify();// 随机唤醒一个线程，在该锁下面的，并尝试获取锁
//        }
//    }
}
